from torch_geometric.nn import GCNConv
import torch, time
from Visualize import visualize
from torch.nn.functional import dropout
from torch_geometric.datasets import Planetoid
from torch_geometric.transforms import NormalizeFeatures


class GCN(torch.nn.Module):
    def __init__(self, dataset, hidden_channels):
        super(GCN, self).__init__()
        torch.manual_seed(12345)
        self.conv1 = GCNConv(dataset.num_features, hidden_channels)
        self.classifier = GCNConv(hidden_channels, dataset.num_classes)

    def forward(self, x, edge_index):
        x = self.conv1(x, edge_index)
        x = x.relu()
        x = dropout(x, p=0.5, training=self.training)
        out = self.classifier(x, edge_index)
        return out


"""
#data = KarateClub()
#print(data.x.shape, data.edge_index.shape, data.y.shape, data.train_mask.shape)
#torch.Size([34, 34]) torch.Size([2, 156]) torch.Size([34]) torch.Size([34])
"""
dataset = Planetoid(root="D:/code/dataset/Planetoid", name="Cora", transform=NormalizeFeatures())
model = GCN(dataset, hidden_channels=128)
print(model)

# 初始可视化展示
model.eval()
data = dataset[0]
out = model(data.x, data.edge_index)
visualize(out, color=data.y)

criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=5e-4)


def train(data):
    model.train()
    optimizer.zero_grad()
    out = model(data.x, data.edge_index)
    loss = criterion(out[data.train_mask], data.y[data.train_mask])
    loss.backward()
    optimizer.step()
    return loss, out


def test(data):
    model.eval()
    out = model(data.x, data.edge_index)
    pred = out.argmax(dim=1)
    test_correct = pred[data.test_mask] == data.y[data.test_mask]
    test_acc = int(test_correct.sum()) / int(data.test_mask.sum())
    return test_acc


def epoch_train(data):
    for epoch in range(1, 901):
        loss, out = train(data)
        if epoch % 30 == 0:
            print(epoch, loss.item())
            visualize(out, color=data.y, epoch=epoch)


# 很好的验证了半监督能力。
epoch_train(data)
print("准确率",test(data))
